﻿using System;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;

using System.ServiceModel.Channels;

namespace ShopPowerTemplate.WcfService.Auth
{
    public class CustomMessageInspector : IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            int userIndex = request.Headers.FindHeader("User", "http://www.icinetic.com");
            int pwdIndex = request.Headers.FindHeader("SessionId", "http://www.icinetic.com");

            if (userIndex == -1 || pwdIndex == -1) throw new InvalidOperationException("Fallo al autenticar");

            string user = request.Headers.GetHeader<string>(userIndex);
            string pwd = request.Headers.GetHeader<string>(pwdIndex);

            if (!CheckUser(user, pwd)) throw new FaultException("Fallo al autenticar", new FaultCode("AUTHENTICATION"));

            return null;
        }

        private bool CheckUser(string user, string pwd)
        {
            ShopPowerTemplate.Services.IAuthenticationService serv = ShopPowerTemplate.IoC.IoCFactory.Resolve<ShopPowerTemplate.Services.IAuthenticationService>();

            return serv.CheckUserPassword(user, pwd);
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
        }
    }
}